<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\Role;
use App\Models\RoleUser;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class RoleService
{
    public function get($search,$project_id,$type = 'company'){
        $sql = Role::select('id','name','status','auth','created_at','project_id')->with('parent')->with('roles')->when($search, function ($query, $search) {
            return $query->where(function($query) use ($search) {
                $query->where('name','like', '%'.$search.'%');
            });
        })
        ->when($project_id, function ($query, $project_id) {
            return $query->where(function($query) use ($project_id) {
                $query->where('project_id',$project_id);
            });
        });
        return $sql;
    }

    public function getAll($project_id){
        $sql = Role::select('id','name','status','auth','created_at')->when($project_id, function ($query, $project_id) {
            return $query->where(function($query) use ($project_id) {
                $query->whereIn('project_id',[0,$project_id]);
            });
        });
        return $sql;
    }

    public function insert($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v || $v == 0){
                $res[$k] = $v;
            }
        }
        $is = Role::where('name',$res['name'])->first();
        if($is){
            throw new InvalidRequestException('这个角色已存在');
        }
        try {
            $res['auth'] = json_encode($res['auth']);
            $res['status'] = $res['status'] ? 1 : 0;
            $res['company_id'] = Auth::user()->company_id;
            $data = Role::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th->getMessage()));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        $res = [];
        foreach ($input as $k => $v) {
            $v = $v === null ? '/' : $v;
            if($v || $v == 0){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $res['auth'] = json_encode($res['auth']);
            $res['status'] = $res['status'] ? 1 : 0;
            $data = Role::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function status($data){
        try {
            $data->status =  $data->status ? 0 : 1;
            $data->save();
            if($data->id){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function insertBindUser($input){
        $userId = json_decode($input['user_id']);
        $certId = json_decode($input['cert_id']);
        RoleUser::where('project_id',$input['project_id'])->where('role_id',$input['role_id'])->delete();
        // $projectBinduser
        foreach ($userId as $key => $value) {
            $arr = [];
            $arr['user_id'] = $value;
            $arr['role_id'] = $input['role_id'];
            $arr['project_id'] = $input['project_id'];
            $arr['cert_id'] = $certId[$key];
            $arr['created_at'] = Date('Y-m-d H:i:s',time());
            $arr['updated_at'] = Date('Y-m-d H:i:s',time());
            $insert[] = $arr;
        }
        // $isUser = RoleUser::where('project_id',$input['project_id'])->where('role_id',$input['role_id'])->pluck('user_id');
        // foreach ($userId as $key => $value) {
        //     $arr = [];
        //     if(count($isUser)){
        //         if(!in_array($value,$isUser)){
        //             $arr['user_id'] = $value;
        //             $arr['role_id'] = $input['role_id'];
        //             $arr['project_id'] = $input['project_id'];
        //             $arr['cert_id'] = $certId[$key];
        //             $arr['created_at'] = Date('Y-m-d H:i:s',time());
        //             $arr['updated_at'] = Date('Y-m-d H:i:s',time());
        //             $insert[] = $arr;
        //         }
        //     }else{
        //         $arr['user_id'] = $value;
        //         $arr['role_id'] = $input['role_id'];
        //         $arr['project_id'] = $input['project_id'];
        //         $arr['cert_id'] = $certId[$key];
        //         $arr['created_at'] = Date('Y-m-d H:i:s',time());
        //         $arr['updated_at'] = Date('Y-m-d H:i:s',time());
        //         $insert[] = $arr;
        //     }
            
        // }
        try {
            $data = RoleUser::insert($insert);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th->getMessage()));
            throw new InternalException('提交失败');
        }
    }

    public function updateBindUser($input){
        try {
            $data = RoleUser::find($input['id']);
            foreach ($input as $k => $v) {
                $data->$k = $v;
            }
            $data->save();
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }
}